<template>
  <div class='seniority-container'>
    <div class="seniority-fun-btn">
      <el-upload class="upload" action="" :multiple="false" :show-file-list="false" accept="csv, application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" :http-request="httpRequest">
        <el-button type="primary" style="margin-right: .7rem">导入表格</el-button>
      </el-upload>
      <el-button type="primary" @click="exportData">导出数据</el-button>
      <el-button type="primary" @click="startCount">开始计算</el-button>
    </div>
    <div class="seniority-table">
      <el-table
        :data="tableData"
        height="100%"
        :default-sort = "{prop: 'data', order: 'descending'}"
        border
        stripe
        :header-cell-style="{ 'text-align': 'center' }"
        :cell-style="{ 'text-align': 'center' }"
        style="width: 100%;">
        <el-table-column
          type="index"
          width="50">
        </el-table-column>
        <el-table-column
          prop="department"
          label="部门"
          width="180">
        </el-table-column>
        <el-table-column
          prop="workers"
          label="工号"
          width="180">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名">
        </el-table-column>
        <el-table-column
          prop="eod"
          label="到职日期">
        </el-table-column>
        <el-table-column
          prop="baseDay"
          label="基准日">
        </el-table-column>
        <el-table-column
          prop="systemService"
          label="系统工龄">
        </el-table-column>
        <el-table-column
          sortable
          prop="calculate"
          label="计算工龄">
        </el-table-column>
        <el-table-column
          sortable
          prop="num"
          label="数值">
        </el-table-column>
        <el-table-column
          prop="seniority"
          label="年资">
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
export default {
  data () {
    return {
      tableData: [
      ],
      search: '',
      seniorityExcel: []
    }
  },
  methods: {
    handleEdit (index, row) {
      console.log(index, row)
    },
    handleDelete (index, row) {
      console.log(index, row)
    },
    // // 处理工资保留两位小数点
    // formatter (row) {
    //   // const num = row.seniority.toFixed(2)
    //   console.log(row)
    //   return row.seniority
    // },
    // 读取excel文件、拼接字段
    httpRequest (e) {
      const file = e.file
      if (!file) {
        return false
      } else if (!/\.(xls|xlsx)$/.test(file.name.toLowerCase())) {
        this.$message.error('上传格式不正确，请上传xls或者xlsx格式')
        return false
      }
      const fileReader = new FileReader()
      fileReader.onload = (ev) => {
        try {
          const data = ev.target.result
          const workbook = XLSX.read(data, {
            type: 'binary'
          })
          const exlname = workbook.SheetNames[0] // 取第一张表
          const exl = XLSX.utils.sheet_to_json(workbook.Sheets[exlname]) // 生成json表格内容
          const ob = [...exl]
          let obs = JSON.stringify(ob)
          obs = obs.replace(/\u90e8\u95e8/g, 'department')
          obs = obs.replace(/\u5de5\u53f7/g, 'workers')
          obs = obs.replace(/\u59d3\u540d/g, 'name')
          obs = obs.replace(/\u5230\u804c\u65e5\u671f/g, 'eod')
          obs = obs.replace(/\u57fa\u51c6\u65e5/g, 'baseDay')
          obs = obs.replace(/\u7cfb\u7edf\u5de5\u9f84/g, 'systemService')
          obs = obs.replace(/\u8ba1\u7b97\u5de5\u9f84/g, 'calculate')
          obs = obs.replace(/\u6570\u503c/g, 'num')
          obs = obs.replace(/\u5e74\u8d44/g, 'seniority')
          this.seniorityExcel = []
          this.seniorityExcel = JSON.parse(obs)
          this.tableData = Object.assign([], this.seniorityExcel)
          console.log(this.seniorityExcel)
          // this.CopyCommunityExcel = []
          // this.CopyCommunityExcel = this.CommunityExcel
          // for (let index = 0; index < this.CopyAppTable.length; index++) {
          //   for (let i = 0; i < this.CopyCommunityExcel.length; i++) {
          //     if (Number(this.CopyAppTable[index].applets) === this.CopyCommunityExcel[i].HouseholdPhone) {
          //       let obj = Object.assign({} ,this.CopyAppTable[index], this.CopyCommunityExcel[i], this.Contrast)
          //       this.tableData.push(obj)
          //       this.obj = {}
          //       this.CopyCommunityExcel.splice(i,1)
          //       i--
          //       this.list = true
          //     }
          //   }
          //   if (this.list) {
          //     this.CopyAppTable.splice(index, 1)
          //     index --
          //     this.list = false
          //   }
          // }
          // this.CopyAppTable.map(item => {
          //   let obj2 = Object.assign({}, item, this.Homeowner)
          //   this.tableData.push(obj2)
          // })
          // this.CopyCommunityExcel.map(item => {
          //   let obj1 = Object.assign({}, this.App, item, this.Contrast)
          //   this.tableData.push(obj1)
          // })
          // this.CopytableData = this.tableData
        } catch (e) {
          this.$message.error('请检查导入数据格式')
          return false
        }
      }
      fileReader.readAsBinaryString(file)
    },
    // 开始计算数据
    startCount () {
      if (this.tableData.length === 0) {
        this.$message({
          message: '没有数据哦，请先导入Excel表格数据',
          type: 'warning'
        })
        return false
      }
      const arr = Object.assign([], this.tableData)
      const ar = arr.map(item => {
        const num = this.countCalculate(`${item.eod}`, `${item.baseDay}`)
        item.calculate = num
        item.num = Number(num) - 12
        // item.seniority = item.num
        if (item.num <= 0) {
          item.seniority = (0).toFixed(2)
        } else {
          item.seniority = (item.num * 40).toFixed(2)
        }
        return item
      })
      this.tableData = Object.assign([], ar)
    },
    // 计算工龄
    countCalculate (startTime, endTime) {
      startTime = new Date(startTime.replace(/-/g, '/'))
      endTime = new Date(endTime.replace(/-/g, '/'))
      var dateToMonth = 0
      var startDate = startTime.getDate() + startTime.getHours() / 24 + startTime.getMinutes() / 24 / 60
      var endDate = endTime.getDate() + endTime.getHours() / 24 + endTime.getMinutes() / 24 / 60
      if (endDate >= startDate) {
        dateToMonth = 0
      } else {
        dateToMonth = -1
      }
      const yearToMonth = (endTime.getYear() - startTime.getYear()) * 12
      const monthToMonth = endTime.getMonth() - startTime.getMonth()
      return yearToMonth + monthToMonth + dateToMonth
    },
    // 导出数据
    exportData () {
      require.ensure([], () => {
        const { exportJsonToExcel } = require('@/vendor/Export2Excel') // 引入js文件
        const tHeader = ['部门', '工号', '姓名', '到职日期', '基准日', '系统工龄', '计算工龄', '数值', '年资'] // table的表头数据，导出后为excel第一行
        const filterVal = ['department', 'workers', 'name', 'eod', 'baseDay', 'systemService', 'calculate', 'num', 'seniority'] // table数据的prop关键字，后面循环要用到
        const list = this.tableData // this.tableData是我的初始填入数据，这里以element-ui的表格为例
        const data = this.formatJson(filterVal, list) // 循环重组数据
        exportJsonToExcel(tHeader, data, 'excel文件名')
      })
    },
    formatJson (filterVal, jsonData) { // 循环重组数据
      return jsonData.map(v => filterVal.map(j => v[j]))
    }
  }
}
</script>

<style lang='scss' scoped>
@import './index.scss'
</style>
